package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.YxdAddEvaluationAdapter;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.r_trrAddtion;
import cn.acewill.yxd.yunxundian.model.reportHeadBean;
import cn.acewill.yxd.yunxundian.model.reportTailBean;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by AAA on 2017/4/14.
 */

public class YxdEvaluationListActivity extends BaseActivity implements View.OnClickListener,TextWatcher {

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private  YxdAddEvaluationAdapter addAdapter;
    private ListView addListView;
    private ArrayList<tempLostRR> rrList;
    private List<tempLostRR> temp;
    private LinearLayout nodata;
    /*判断页面传递来的schid*/
    public  int schid;
    private TextView textSure;
    private Button jibenData;
    private  RMain.QBean qinfo;
    private EditText remarks,managername;
    private  int reportMainid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.yxd_evaluation_list);
        super.onCreate(savedInstanceState);
        CacheActivity.addActivity(this);
        initView();

        try {
            initDate();
            ifJibenVisible();
            getTishiInfo();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public void initView(){
        int tag=getIntent().getIntExtra("rrschid",-1);
        if (tag!=-1){
            schid=tag;
            gudingSchid(schid);
        }
        try {
            checkCanDoReport();
        } catch (DbException e) {
            e.printStackTrace();
        }
        ImageView toastImg = (ImageView) findViewById(R.id.toastImg);
        toastImg.setOnClickListener(this);
        this.jibenData= (Button) findViewById(R.id.jibenData);
        jibenData.setOnClickListener(this);

        ImageView addTask = (ImageView) findViewById(R.id.addTask);
        addTask.setOnClickListener(this);
        this.addListView= (ListView) findViewById(R.id.addListView);
        this.nodata= (LinearLayout) findViewById(R.id.nodata);
        TextView submitData = (TextView) findViewById(R.id.submitData);
        submitData.setOnClickListener(this);

    }

//    public void initHeadView(){
//        View headview = LayoutInflater.from(this).inflate(R.layout.addition_info_view,null);
//        this.managername= (EditText) headview. findViewById(R.id.managerName);
//        this.remarks= (EditText) headview.findViewById(R.id.remarks);
//        managername.addTextChangedListener(this);
//        this.textSure= (TextView) headview.findViewById(R.id.textSure);
//        this.textSure.setOnClickListener(this);
//
//        addListView.addHeaderView(headview);
//    }

    public String refreshScore(int schid)throws DbException
    {
        TextView titleText = (TextView)findViewById(R.id.textTitle);
        String retStr="";
        if(titleText!=null) {
            retStr=pubClass.calScoreBySch(schid);
            titleText.setText(retStr);
        }
        return retStr;
    }
    public void ifJibenVisible() throws DbException {
        List<reportHeadBean>  mheadList= db.selector(reportHeadBean.class).where("reportMainID","=",reportMainid).orderBy("orderValue").findAll();
        List<reportTailBean> mtailList=db.selector(reportTailBean.class).where("reportMainId","=",reportMainid).orderBy("orderValue").findAll();
        if ((mheadList!=null&&mheadList.size()>0)||(mtailList!=null&&mtailList.size()>0)){
            jibenData.setVisibility(View.VISIBLE);
        }else{
            jibenData.setVisibility(View.GONE);
        }
    }

    public void gudingSchid(int thisSchid)
    {
        try {
            CommonMapBean gudingSch=db.selector(CommonMapBean.class).where("cmType","=","gudingsch").findFirst();
            if(gudingSch!=null)
            {
                gudingSch.setCmValue(thisSchid+"");
            }
            else{
                gudingSch=new CommonMapBean();
                gudingSch.setCmValue(thisSchid+"");
            }
            db.saveOrUpdate(gudingSch);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void jiuyuanSchid()
    {
        try {
            CommonMapBean gudingSch=db.selector(CommonMapBean.class).where("cmType","=","gudingsch").findFirst();
            if(gudingSch!=null)
            {
                schid=Integer.getInteger(gudingSch.getCmValue(),0);
            }
            else
                schid=0;
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    //获取提示的信息
    public void getTishiInfo() throws DbException {
        Schedule schedule = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
        sType type = db.selector(sType.class).where("ID", "=", schedule.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        if (rMains!=null&&rMains.size()>0){
            qinfo = rMains.get(0).getQ();
            RMain.TablesBean tablesBean=rMains.get(0).getTables().get(0);
            reportMainid= tablesBean.getQ1().getReportMainID();
        }

    }


    public void checkCanDoReport() throws DbException
    {
        if(schid==0)
            jiuyuanSchid();
        final Schedule thisSch=db.selector(Schedule.class).where("ID","=",schid+"").findFirst();
        refreshScore(schid);

        if(thisSch.getShopID()>0)
        {
            if(thisSch.getStates()==1) {
                SignUpInfo sui = db.selector(SignUpInfo.class).where("shopId", "=", thisSch.getShopID())
                        .and("empId","=", MainActivity.id)
                        .and("outTime","=",null)
                        .findFirst();
                if(sui==null){
                    MaterialDialogUtils.showMaterialDialog(this, "当前门店没进行签到，是否去该门店签到？"+"\n"+"tip：签到才能执行任务",
                            "确定", "取消", false,true,
                            new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                    try {
                                        Shop shop = db.selector(Shop.class).where("ID","=",thisSch.getShopID()).findFirst();
                                        Intent in=new Intent(YxdEvaluationListActivity.this,SignInActivity.class).putExtra("shopId",thisSch.getShopID());
                                        in.putExtra("xcol",shop.getxCol());
                                        in.putExtra("ycol", shop.getyCol());
                                        in.putExtra("schid",schid);
                                        in.putExtra("shopName", shop.getShopName());
                                        startActivity(in);
                                        finish();

                                    } catch (DbException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }, new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });

                }
                else{
                    thisSch.setStates(2);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    String thistime=df.format(new Date());
                    thistime=thistime.replace(" ","T");
                    thisSch.setRealStartTime(thistime);
                    db.saveOrUpdate(thisSch);
                }
            }
        }
    }

    public void initDate() throws DbException {
        //加载本地的数据
        temp=db.selector(tempLostRR.class).where("schId","=",schid).findAll();
        if (temp!=null &&temp.size()!=0){
            addListView.setVisibility(View.VISIBLE);
            nodata.setVisibility(View.GONE);
            rrList=new ArrayList<>();
            rrList.addAll(temp);
            addAdapter=new YxdAddEvaluationAdapter(this, rrList, new YxdAddEvaluationAdapter.BtnOnClickLisener() {
                @Override
                public void modifiClick(tempLostRR bean) {
                    Intent in=new Intent(YxdEvaluationListActivity.this,MarkPhotoActivity.class);
                    in.putExtra("_ID",bean.get_ID());
                    in.putExtra("tag",2);
                    in.putExtra("type",bean.getScoreType());
                    in.putExtra("schid",schid);
                    startActivity(in);
                }
                @Override
                public void deleteClick(final int position) {
                    MaterialDialogUtils.showMaterialDialog(YxdEvaluationListActivity.this, "是否删除当前评估项", "确定", "取消", true,false
                            , new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    try {
                                        tempLostRR bean=rrList.get(position);
                                        List<r_trrAddtion> trraList = db.selector(r_trrAddtion.class).where("schid","=",schid).and("rowId","=",bean.getRRowId()).findAll();
                                        if(trraList!=null){
                                            db.delete(trraList);
                                        }
                                        db.deleteById(tempLostRR.class,bean.get_ID());
                                        rrList.remove(position);
                                        addAdapter.notifyDataSetChanged();

                                        refreshScore(schid);
                                        if (rrList==null||rrList.size()==0){
                                            addListView.setVisibility(View.GONE);
                                            nodata.setVisibility(View.VISIBLE);
                                        }
                                    } catch (DbException e) {
                                        e.printStackTrace();

                                    }
                                }
                            }, new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                }});
                }
            });
            addListView.setAdapter(addAdapter);
        }else{
            addListView.setVisibility(View.GONE);
            nodata.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addTask:
                Intent in = new Intent(this, YxdMajorMainActivity.class).putExtra("schid", schid);
                startActivity(in);
                break;
            case R.id.submitData:
                String title;
                if (temp == null || temp.size() <= 0) {
                    title = "该评估表尚未填写任何失分项，是否进行提交";
                } else {
                    title = "是否进行数据提交";
                }
                MaterialDialogUtils.showMaterialDialog(this, title, "确定", "取消", true, false
                        , new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                Intent in = new Intent(YxdEvaluationListActivity.this, SendMailActivity.class).putExtra("schId", schid);
                                //添加一个类型，用于关闭当前的页面
                                startActivityForResult(in, 101);
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            }
                        });
                break;
            case R.id.toastImg:
                if (qinfo != null) {
                    if (qinfo.getDescription() != null && !TextUtils.isEmpty(qinfo.getDescription())) {
                        //创建提示框
                        Log.e("qinof", qinfo.getDescription());
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        View dview = LayoutInflater.from(this).inflate(R.layout.normal_text_view, (ViewGroup) getWindow().getDecorView(), false);
                        builder.setView(dview);
                        builder.setTitle("提示信息");
                        TextView mytext = (TextView) dview.findViewById(R.id.mytext);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            mytext.setText(Html.fromHtml(qinfo.getDescription(), Html.FROM_HTML_MODE_COMPACT));
                        } else {
                            mytext.setText(Html.fromHtml(qinfo.getDescription()));
                        }

                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        builder.show();
                    } else Toast.makeText(this, "暂无提示信息", Toast.LENGTH_SHORT).show();
                } else Toast.makeText(this, "暂无提示信息", Toast.LENGTH_SHORT).show();

                break;
            case R.id.textSure:
                if (textSure.getText().equals("完成")) {
                    String nameText = managername.getText().toString().trim();
                    String remarkText = remarks.getText().toString().trim();
                    managername.setEnabled(false);
                    remarks.setEnabled(false);
                    textSure.setText("修改");
                    textSure.setTextColor(getResources().getColor(R.color.red));

                } else {
                    managername.setEnabled(true);
                    remarks.setEnabled(true);
                    textSure.setText("完成");
                    textSure.setTextColor(getResources().getColor(R.color.titleColor));
                }

                break;
            case R.id.jibenData:
                startActivity(new Intent(this, JibenInfoActivity.class).putExtra("mainId", reportMainid).putExtra("schid",schid));
                break;
            case R.id.doSign:

                break;
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 101:
                finish();
                break;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
            return false;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //保存输入的数据
        if (!TextUtils.isEmpty(managername.getText().toString().trim()))
            textSure.setVisibility(View.VISIBLE);
        else textSure.setVisibility(View.GONE);
    }




}
